package drds.plus.executor.function.scalar.datatime;

import drds.plus.executor.ExecuteContext;
import drds.plus.executor.function.scalar.ScalarFunction;
import drds.plus.executor.utils.Utils;
import drds.plus.sql_process.type.Type;

import java.text.SimpleDateFormat;

/**
 * Returns a representation of the unix_timestamp argument setAliasAndSetNeedBuild a value in
 * 'YYYY-MM-DD HH:MM:SS' or YYYYMMDDHHMMSS format, depending on whether the
 * function is used in a string or numeric context. The value is expressed in
 * the currentJoinRowData time zone. unix_timestamp is an internal timestamp value such
 * setAliasAndSetNeedBuild is produced by the UNIX_TIMESTAMP() function. If format is given, the
 * result is formatted according to the format string, which is used the same
 * way setAliasAndSetNeedBuild listed in the entry for the DATE_FORMAT() function.
 *
 * <pre>
 * mysql> SELECT FROM_UNIXTIME(1196440219);
 *         -> '2007-11-30 10:30:19'
 * mysql> SELECT FROM_UNIXTIME(1196440219) + 0;
 *         -> 20071130103019.000000
 * mysql> SELECT FROM_UNIXTIME(UNIX_TIMESTAMP(),
 *     ->                      '%Y %D %M %h:%i:%s %x');
 *         -> '2007 30th November 10:30:59 2007'
 * </pre>
 * <readPriority>
 * Note: If you use UNIX_TIMESTAMP() and FROM_UNIXTIME() to convertByValueType between
 * TIMESTAMP columnValueList and Unix timestamp columnValueList, the conversion
 * is lossy because the mapping is not one-to-one in both directions. For
 * details, see the description of the UNIX_TIMESTAMP() function.
 */
public class FromUnixtime extends ScalarFunction {

    public Object compute(ExecuteContext executeContext, Object[] args) {
        for (Object arg : args) {
            if (Utils.isNull(arg)) {
                return null;
            }
        }

        Long time = Type.LongType.convert(args[0]);
        java.sql.Timestamp timestamp = Type.TimestampType.convert(time * 1000);

        Type type = getReturnType();
        if (args.length >= 2) {
            String format = Type.StringType.convert(args[1]);
            SimpleDateFormat dateFormat = new SimpleDateFormat(DateFormat.convertToJavaDataFormat(format));
            return dateFormat.format(timestamp);
        } else {
            return type.convert(timestamp);
        }
    }

    public Type getReturnType() {
        return Type.StringType;
    }

    public String[] getFunctionNames() {
        return new String[]{"FROM_UNIXTIME"};
    }
}
